package fxserversocket

import (
	"fmt"
	"golang.org/x/net/websocket"
	"net"

)


func TcpSocketStart(addr string,webaddr string) {
	//定义一个tcp断点
	var tcpAddr *net.TCPAddr
	//通过ResolveTCPAddr实例一个具体的tcp断点
	tcpAddr, _ = net.ResolveTCPAddr("tcp", addr)
	//打开一个tcp断点监听
	tcpListener, _ := net.ListenTCP("tcp", tcpAddr)
	defer tcpListener.Close()

	//循环接收客户端的连接，创建一个协程具体去处理连接
	for {
		tcpConn, err := tcpListener.AcceptTCP()
		if err != nil {
			fmt.Println(err)
			continue
		}

		go tcpPipe(tcpConn,webaddr)
	}
}

//具体处理连接过程方法
func tcpPipe(conn *net.TCPConn,webaddr string) {

	//tcp连接的地址
	ipStr := conn.RemoteAddr().String()
	exit_sta:=false
	fmt.Printf("tcpPipe start ws conn ,wewsoketaddr=%s,ip=%s\n","ws://"+webaddr ,ipStr)
	var wsurl = "ws://"+webaddr
	var origin = "http://"+webaddr
	defer func() {
		fmt.Printf("websocket  err recover()") //有效
		fmt.Println(recover()) //有效
		if exit_sta!=true{
			conn.Close()
		}
	}()
	ws, err := websocket.Dial(wsurl, "", origin)

	defer func() {
		ws.Close()


		fmt.Printf("tcpPipe ws conn close,ip=%s\n", ipStr)
	}()
	if err != nil {
		return
	}
	go func(){
		defer func() {
			exit_sta=true
			conn.Close()
		}()
		for {
			var webbuf [1024]byte
			webbufLen, err := ws.Read(webbuf[:])
			if err != nil {
				fmt.Printf("websocket err,ip=%s err: %v\n", ipStr, err)
				break
			}
			conn.Write(webbuf[:webbufLen])
			fmt.Printf("websocket read,ip=%s,data: %v\n", ipStr, webbuf[:webbufLen])
		}
	}()

    for {
        var tcpbuf [1024]byte
		tcpbufLen, err := conn.Read(tcpbuf[:])
 
        if err != nil {
			fmt.Printf("tcpPipe err,ip=%s err: %v\n",ipStr, err)
            break
        }
        ws.Write(tcpbuf[:tcpbufLen])
		fmt.Printf("tcpPipe read,ip=%s,data: %v\n", ipStr, tcpbuf[:tcpbufLen])
    }
}

 

